import sys
import time
import json
from typing import Any
from loguru import logger
import httpx
from mcp.server.fastmcp import FastMCP

from loguru import logger

# 初始化日志配置
logger.add("logs/search.log", rotation="100 MB", level="DEBUG")
logger.add(sys.stderr, level="INFO")

# Initialize FastMCP server
mcp = FastMCP("search")


# Constants
NWS_API_BASE = "http://127.0.0.1:3001"
USER_AGENT = "search-app/1.0"

async def make_nws_request(url: str) -> dict[str, Any] | None:
    """Make a request to the NWS API with proper error handling."""
    headers = {
        "User-Agent": USER_AGENT,
        "Accept": "application/geo+json"
    }
    async with httpx.AsyncClient() as client:
        try:
            response = await client.get(url, headers=headers, timeout=30.0)
            response.raise_for_status()
            return response.json()
        except Exception:
            return None

def format_alert(feature: dict) -> str:
    """Format an alert feature into a readable string."""
    props = feature["properties"]
    return f"""
Event: {props.get('event', 'Unknown')}
Area: {props.get('areaDesc', 'Unknown')}
Severity: {props.get('severity', 'Unknown')}
Description: {props.get('description', 'No description available')}
Instructions: {props.get('instruction', 'No specific instructions provided')}
"""

@mcp.tool()
async def search1(keyword: str) -> str:
    """通过关键词获取最新网络信息，适用于需要实时数据的场景。
    Args:
        keyword: 搜索关键词（如 "ChatGPT", "人工智能"）
    
    """
    # 输入验证
    if not keyword.strip():
        logger.warning("收到空关键词请求")
        return "Invalid keyword: empty input"
    
    # 记录入参
    logger.info(f"[请求入口] 收到搜索请求 - 关键词: {keyword}")
    start_time = time.time()
    # 删除重复的计时初始化
    # start_time = time.time()  # 初始化计时起点
    
    # 构造请求URL
    url = f"{NWS_API_BASE}/api/search?keyword={keyword}&pages=1"
    data = await make_nws_request(url)
    
    # 记录响应
    logger.debug(f"[接口响应] 原始数据: {json.dumps(data, ensure_ascii=False)}")
    logger.info(f"请求处理完成 - 耗时: {time.time() - start_time:.2f}s")
    
    if not data:
        logger.error("接口请求失败 - 关键词: {}", keyword)
        return "No data found or failed to fetch."

    # 假设返回格式为：{ "results": [ { "title": ..., "url": ..., "snippet": ... }, ... ] }
    results = data.get("data", [])
    if not results:
        return "No search results."

    # 格式化结果
    logger.success("成功返回{}条搜索结果 - 耗时:{:.2f}s".format(len(results), time.time()-start_time))
    return "\n---\n".join([
        f"Title: {r.get('title')}\nURL: {r.get('url')}\nSnippet: {r.get('snippet')}"
        for r in results
    ])

@mcp.tool()
async def weather(keyword: str) -> str:
   """获取天气功能。
    Args:
        keyword: 搜索关键词（如 "天气如何？"）
   """
   return "今天天气很好！"


if __name__ == "__main__":
    # # Initialize and run the server
    # # 添加参数解析
    # import argparse
    # parser = argparse.ArgumentParser()
    # parser.add_argument('--enable-auto-tool-choice', action='store_true')
    # parser.add_argument('--tool-call-parser', action='store_true')
    # args = parser.parse_args()
    
    # # 记录加载参数
    # logger.info(f"启动参数检测：auto_tool_choice={args.enable_auto_tool_choice}, tool_call_parser={args.tool_call_parser}")
    # # 在mcp.run之前添加参数应用逻辑
    # if args.enable_auto_tool_choice and args.tool_call_parser:
    #     mcp.enable_auto_tool_choice = True
    #     mcp.tool_call_parser = "auto"
    #     logger.info("已启用自动工具选择模式")
    # else:
    #     logger.warning("未启用自动工具选择模式")
    
    logger.info("MCP服务启动，使用stdio传输协议")
    mcp.run(transport='stdio')
